﻿#include "CVlcSdkOper.h"
#include<QThread>
CVlcSdkOper::CVlcSdkOper()
{
	m_bRealPlay = false;
	m_pVlcInstance = libvlc_new(0, nullptr);  // 初始化libVLC 创建libVLC实例
	m_pVlcMediaPlayer = libvlc_media_player_new(m_pVlcInstance); // 创建一个媒体播放器MediaPlayer
}

CVlcSdkOper::~CVlcSdkOper()
{
	if (m_pMedia != nullptr)
	{
		libvlc_media_release(m_pMedia);
		m_pMedia = nullptr;
	}
	libvlc_media_player_release(m_pVlcMediaPlayer);
	m_pVlcMediaPlayer = nullptr;
	libvlc_release(m_pVlcInstance);
	m_pVlcInstance = nullptr;
}

bool CVlcSdkOper::realPlay(const QString sRtspUrl, WId winId)
{
	if (m_bRealPlay)
	{
		stopRealPlay();
	}
	libvlc_media_player_set_hwnd(m_pVlcMediaPlayer, reinterpret_cast<void*>(winId));
	m_pMedia = libvlc_media_new_location(m_pVlcInstance, sRtspUrl.toStdString().c_str());
	if (m_pMedia == nullptr)
	{
		return false;
	}
	libvlc_media_player_set_media(m_pVlcMediaPlayer, m_pMedia);
	if (libvlc_media_player_play(m_pVlcMediaPlayer) == 0)
	{
		m_bRealPlay = true;
		return true;
	}
	else
	{
		m_bRealPlay = false;
		return false;
	}
}

bool CVlcSdkOper::realPlay(const QString sRtspUrl, WId winId, QString & sReInfo)
{
	if (m_bRealPlay)
	{
		return true;
	}
	if (m_pMedia == nullptr)
	{
		m_pMedia = libvlc_media_new_location(m_pVlcInstance, sRtspUrl.toStdString().c_str());
		if (m_pMedia == nullptr)
		{
			sReInfo = "libvlc_media_new_location fail";
			return false;
		}
	}
	libvlc_media_player_set_media(m_pVlcMediaPlayer, m_pMedia);
	libvlc_media_player_set_hwnd(m_pVlcMediaPlayer, reinterpret_cast<void*>(winId));
	if (libvlc_media_player_play(m_pVlcMediaPlayer) == 0)
	{
		sReInfo = "replay suc";
		m_bRealPlay = true;
		return true;
	}
	else
	{
		sReInfo = "replay fail";
		m_bRealPlay = false;
		return false;
	}
}


bool CVlcSdkOper::stopRealPlay()
{
	libvlc_media_player_stop(m_pVlcMediaPlayer);//关闭视频
	if (m_pMedia != nullptr)
	{
		libvlc_media_release(m_pMedia);
		m_pMedia = nullptr;
	}
	m_bRealPlay = false;
	//QThread::msleep(500);
	return true;
}

bool CVlcSdkOper::stopRealPlayEx()
{
	if (!m_bRealPlay)
	{
		return true;
	}
	else
	{
		libvlc_media_player_stop(m_pVlcMediaPlayer);//关闭视频
		m_bRealPlay = false;
		return true;
	}	
}

void CVlcSdkOper::setSuspendText(const QString sShowText, const int nColorType)
{
	if (m_pVlcMediaPlayer != nullptr)
	{
		libvlc_video_set_marquee_int(m_pVlcMediaPlayer, libvlc_marquee_Enable, 1);
		libvlc_video_set_marquee_string(m_pVlcMediaPlayer, libvlc_marquee_Text, sShowText.toStdString().c_str());
		libvlc_video_set_marquee_int(m_pVlcMediaPlayer, libvlc_marquee_Position, 9);
		libvlc_video_set_marquee_int(m_pVlcMediaPlayer, libvlc_marquee_X, 20);
		libvlc_video_set_marquee_int(m_pVlcMediaPlayer, libvlc_marquee_Y, 20);
		if (nColorType == 0)//绿色
		{
			libvlc_video_set_marquee_int(m_pVlcMediaPlayer, libvlc_marquee_Color, 0x00ff00);
		}
		else if (nColorType == 1)//红色
		{
			libvlc_video_set_marquee_int(m_pVlcMediaPlayer, libvlc_marquee_Color, 0xff0000);
		}
	}
}
